<template>
  <div class="container">
    <el-scrollbar class="events">
      <div class="label-out">{{ $t('事件类型配置') }}</div>
      <div class="form">
        <div class="label">{{ $t('事件类型名称') }}</div>
        <div class="events-input">
          <el-input v-model="eventName" :placeholder="$t('请输入要添加的事件类型')" />
        </div>
      </div>
      <div class="form">
        <div class="label">{{ $t('严重程度') }}</div>
        <div class="events-input">
          <el-select v-model="eventLevel" :placeholder="$t('AI严重程度判断')" size="large" style="width: 413px" clearable>
            <el-option v-for="item in eventLevels" :key="item.dictValue" :label="item.dictLabel"
                       :value="item.dictValue" />
          </el-select>
        </div>
      </div>
      <el-button type="primary" size="large" @click="addEvent">{{ $t('提交') }}</el-button>
      <div class="label" style="margin-top: 30px">
        {{ $t('已添加的事件') }}（{{eventTypes.length}}）
      </div>
      <div class="events-list">
        <div v-for="item in eventTypes" class="event-item" :key="item.id">
          <div>
            <span :class="item.eventLevel == 1
              ? 'normal'
              : item.eventLevel == 2
                ? 'warning'
                : 'danger'
              "></span>
            {{ item.eventName }}
          </div>
          <i class="iconfont icon-shanchu" @click="deleteItem(item.id)"></i>
        </div>
      </div>
      <div class="divider"></div>
      <div class="label-out">{{ $t('事件判断测试') }}</div>
      <div class="form">
        <el-upload class="import" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                   :auto-upload="true" :on-success="handleUploadSuccess" :on-error="handleUploadError" :data="{}" accept="*"
                   :before-upload="beforeUpload">
          <div class="import">
            <div class="icon">
              <span class="iconfont icon-shangchuan1"></span>
            </div>
            <span class="text">{{ $t('上传文件测试') }}</span>
          </div>
        </el-upload>
      </div>
      <el-table :data="tableData" style="width: 100%;margin-bottom: 150px">
        <el-table-column property="id" :label="$t('ID')" width="100" />
        <el-table-column property="eventName" :label="$t('事件名称')" width="200" />
        <el-table-column property="eventLevel" :label="$t('严重程度')" width="200">
          <template #default="scope">
            {{ getLevelName(scope.row.eventLevel) }}
          </template>
        </el-table-column>
        <el-table-column property="eventImg" :label="$t('图片')">
          <template #default="scope">
            <img :src="scope.row.eventImg" alt="" class="event-img" />
          </template>
        </el-table-column>
        <el-table-column property="aiDisposal" :label="$t('处置方式')" />
        <el-table-column property="eventTime" :label="$t('时间')" width="200" />
      </el-table>
    </el-scrollbar>
  </div>
</template>


<script>
import { ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import { mapGetters } from 'vuex';
import { addEvent, getEventType, deleteEvent } from '@/api/index';
export default {
  name: 'Events',
  props: {},
  components: {},
  data() {
    return {
      uploadUrl: `${process.env.VUE_APP_BASE_API}yswn/WnEvent/testImages`,
      uploadHeaders: {
        Token: `${localStorage.getItem('token')}`,
      },
      eventName: '',
      eventLevel: '',
      eventTypes: [],
      selections: [],
      tableData: [],
      loading: null,
    };
  },
  computed: {
    ...mapGetters({
      dicts: 'dictionary/allDictionaries',
    }),
    eventLevels() {
      let item = this.dicts.filter(
        (item) => item.dictType == 'wn_event_level',
      )[0];
      if (item) {
        return item.dataList;
      } else {
        return [];
      }
    },
  },
  methods: {
    deleteItem(id) {
      ElMessageBox.confirm(
          this.$t('删除该事件类型后不能恢复，确定要删除吗？'),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteEvent([id]); // 删除单个事件
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.getEventType(); // 刷新数据
              } else {
                ElMessage({
                  type: 'error',
                  message: this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.error(this.$t('删除请求失败，请稍后再试'), error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },

    getLevelName(value) {
      if (this.eventLevels) {
        let target = this.eventLevels.filter(item => item.dictValue == value)[0];
        if (target) {
          return target.dictLabel;
        } else {
          return value;
        }
      } else {
        return value;
      }
    },

// 上传前设置 loading 状态
    beforeUpload() {
      this.loading = ElLoading.service({
        lock: true,
        text: this.$t('Loading'),
        background: 'rgba(0, 0, 0, 0.7)',
      });
    },

// 处理上传成功
    handleUploadSuccess(response, file, fileList) {
      if (this.loading) {
        this.loading.close();
      }
      if (response.code === 0) {
        ElMessage({
          type: 'success',
          message: this.$t('文件上传成功!'),
        });
        this.tableData = response.data;
        this.refresh = true;
      }
    },
    handleUploadError(err, file, fileList) {
      if (this.loading) {
        this.loading.close();
      }
      ElMessage({
        type: 'error',
        message: this.$t('文件上传失败!'),
      });
    },

    async addEvent() {
      if (!this.eventName) {
        ElMessage({
          type: 'error',
          message: this.$t('请输入事件类型名称'),
        });
        return;
      }
      if (!this.eventLevel) {
        ElMessage({
          type: 'error',
          message: this.$t('请输入事件严重程度'),
        });
        return;
      }
      const { data } = await addEvent({
        eventName: this.eventName,
        eventLevel: this.eventLevel,
      });
      if (data.code == 0) {
        this.getEventType();
      }
    },

    async getEventType() {
      try {
        const { data } = await getEventType();
        if (data.code === 0) {
          this.eventTypes = data.data;
        }
      } catch (error) {
        console.error(this.$t('事件类型获取失败'), error);
      }
    },

  },
  mounted() {
    this.getEventType();
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100% - 60px);
  background: #181818;
  box-shadow: 12px 12px 30px 0px rgba(40, 58, 44, 0.08);
  border-radius: 32px 32px 32px 32px;
  overflow: hidden;

  .events {
    padding: 20px 25px;

    .event-img {
      object-fit: contain;
      width: 200px;
      height: 120px;
    }

    .label {
      font-weight: 400;
      font-size: 18px;
      color: #ffffff;
      width: 200px;
    }

    .events-list {
      width: 100%;
      height: 292px;
      background: #000000;
      border-radius: 32px 32px 32px 32px;
      margin: 30px 0 35px;
      padding: 12px 0;

      .event-item {
        width: calc(94% / 4);
        margin-right: 2%;
        font-weight: 500;
        font-size: 18px;
        color: #ffffff;
        text-align: center;
        line-height: 60px;
        display: inline-flex;
        justify-content: space-between;

        &>div {
          display: inline-flex;
          align-items: center;

          span {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: inline-block;
            margin-left: 20px;
            margin-right: 10px;

            &.danger {
              border: 4px solid #ff7171;
            }

            &.warning {
              border: 4px solid #ffcc00;
            }

            &.normal {
              border: 4px solid #1fd267;
            }
          }
        }


        i {
          font-size: 20px;
          transition: 0.3s ease;
          cursor: pointer;

          &:hover {
            color: $color;
          }
        }

        &:nth-of-type(4n) {
          margin-right: 0;
        }
      }
    }

    .divider {
      width: 100%;
      height: 1px;
      border-bottom: 1px solid #3b3b3b;
      margin-bottom: 26px;
      margin-top: 26px;
    }

    .label-out {
      font-weight: 400;
      font-size: 24px;
      color: #ffffff;
      line-height: 60px;
      margin-bottom: 20px;
    }

    .form {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
    }
  }
}
</style>
<style lang="scss">
.events-input {
  .el-input__wrapper {
    padding: 0;
    border-radius: 8px;
    overflow: hidden;
  }

  .el-input {
    width: 413px;

    .el-input__inner {
      width: 413px;
      box-shadow: none;
      height: 46px;
      background: #000000;
      color: #fff;
      padding: 8px 16px;
    }
  }
}

.import {
  width: 176px;
  height: 50px;
  background: #303f2e;
  border-radius: 30px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: 0.3s ease;

  .icon {
    width: 32px;
    height: 32px;
    background: $color;
    color: #fff;
    text-align: center;
    line-height: 32px;
    border-radius: 50%;
    margin-right: 10px;
  }

  .text {
    font-weight: 400;
    font-size: 16px;
    color: #ffffff;
    transition: 0.3s ease;
  }

  &:hover {
    background: #fff;

    .text {
      color: $color;
    }
  }
}
</style>
